const http = require('http');
const fs = require('fs').promises;
const path = require('path');

const hostname = '127.0.0.1';
const port = 3000;
const saveDirectory = path.join(__dirname, 'saved_images');
const idiomsFile = path.join(__dirname, 'idioms.json');

// 确保保存图像的目录存在
fs.mkdir(saveDirectory, {recursive: true}).then();

let idioms;

// 读取成语数据
fs.readFile(idiomsFile, 'utf8')
    .then(data => {
        idioms = JSON.parse(data);
    })
    .catch(err => {
        console.error('Error reading idioms file:', err);
    });

// 设置CORS头
const setCORSHeaders = (res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Max-Age', 86400);
};

// 处理POST请求的图片保存
const handleSaveImage = async (req, res) => {
    try {
        const body = await getRequestBody(req);
        const imgData = JSON.parse(body).imgData.replace(/^data:image\/png;base64,/, '');
        const buffer = Buffer.from(imgData, 'base64');
        const fileName = `admin-${Date.now()}.png`;
        const filePath = path.join(saveDirectory, fileName);

        await fs.writeFile(filePath, buffer);

        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify({message: 'Image saved successfully', filePath}));
    } catch (err) {
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end('Error saving the image');
    }
};

// 处理GET请求的成语获取
const handleGetIdiom = (res) => {
    const randomIdiom = idioms[Math.floor(Math.random() * idioms.length)];
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(randomIdiom));
};

// 读取请求体
const getRequestBody = (req) => {
    return new Promise((resolve, reject) => {
        let body = '';
        req.on('data', chunk => body += chunk.toString());
        req.on('end', () => resolve(body));
        req.on('error', reject);
    });
};

const server = http.createServer((req, res) => {
    if (req.method === 'OPTIONS') {
        setCORSHeaders(res);
        res.writeHead(204);
        res.end();
        return;
    }

    setCORSHeaders(res);

    if (req.url === '/save-image' && req.method === 'POST') {
        handleSaveImage(req, res).then();
    } else if (req.url === '/get-idiom' && req.method === 'GET') {
        handleGetIdiom(res);
    } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('Not Found');
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
